<template>
  <el-dialog v-model="isShowDialog"
             :before-close="handleClose"
             title="商品库标签打印"
             draggable
             width="80%"
  >
    <div>
      <el-button type="danger" @click="batchDelete">删除所选</el-button>
    </div>
    <vxe-table
        ref="tablePrintRef"
        border
        :row-config="{isCurrent: true, isHover: true}"
        style="margin-top: 10px;"
        align="center"
        :data="tableData"
        height="400"
        :checkbox-config="{ trigger:'row'}">
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="seq" width="80" title="序号"></vxe-column>
      <vxe-column field="skuCode" width="200" title="SKU编码"></vxe-column>
      <vxe-column field="skuName" width="220" title="商品名称"/>
      <vxe-column field="locationCode" width="220" title="库位编码"/>
      <vxe-column field="locationName" width="220" title="库位位置"/>
      <vxe-column field="rackNo" width="150" title="货架号"/>
      <vxe-column width="150" title="打印数量">
        <template #header>
          <span>打印数量</span>
          <el-button style="margin-left: 20px;" type="text" @click="clickBatchNum">批下</el-button>
        </template>
        <template #default="{row}">
          <el-input v-model="row.printNum" @input="row.printNum=limitIntNumber(row.printNum)" @change="changePrintNum" clearable/>
        </template>
      </vxe-column>
      <vxe-column fixed="right" width="150" title="操作">
        <template #default="{row}">
          <el-button type="text" style="color:green" @click="clickView(row)">预览</el-button>
          <el-button type="text" style="color:red" @click="handleDelete(row)">删除</el-button>
        </template>
      </vxe-column>

    </vxe-table>
    <div style="margin: 10px 0;">
      <span>打印数量合计: <span style="font-size: 18px;color: red;">{{printNumTotal}}</span></span>
      <span style="margin-left: 10px;">模板:
        <el-select
            style="width: 230px;"
            v-model="printTemp"
            @change="changeTemp"
        >
          <template v-for="(item,index) in printTempList" :key="index">
            <el-option :label="item.configName" :value="item.printConfigId"></el-option>
          </template>
        </el-select>
      </span>
      <span style="margin-left: 10px;">
        打印机:
        <el-select v-model="printMachine" clearable placeholder="打印机" style="width: 300px">
          <template v-for="(item,index) in printNameList" :key="index">
            <el-option
                :label="item"
                :value="item"
            />
          </template>
        </el-select>
      </span>
      <el-button style="margin-left: 10px;" type="primary" @click="clickPrint">打印</el-button>
      <el-button style="margin-left: 10px;" type="primary" @click="clickPrintAndClose">打印并返回</el-button>
    </div>

    <!--    打印区域-->
    <div style="display: none">
      <template v-for="(item,index) in printData" :key="index">
        <div :id="'printDiv'+item.putawayId">
          <div style="width: 100%;">
            <svg :id="'barcode'+item.putawayId"></svg>
            <div  style="font-size: 6pt;width: 90%;margin-left: 10px;">
              <div class="skuFont">
               <div v-if="tempStyle =='1'">SKU编码:{{ item.skuCode }}</div>
              <div>商品名称: {{ item.skuName }}</div>
               <div>推荐库位:{{item.locationCode}}</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>

  </el-dialog>
</template>

<script setup>
import {getCurrentInstance, nextTick, onMounted} from "vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {getLodop} from "@/assets/LodopFuncs";
import {getPrintConfigList} from "@/api/scApi";
import JsBarcode from "jsbarcode";
import {limitIntNumber} from "@/utils/shuangcheng";

const {proxy} = getCurrentInstance();
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false
  },
  title: {type: String},
  detailData: {type: Object},
  isView: {type: Boolean}
})
let tableData = ref([])
let printTemp = ref("") //打印模板
let printTempList = ref([]) //打印模板集合
let printMachine = ref("") //打印机名称
let printNameList = ref([])
let printData = ref([]) //打印的数据
let printNumTotal =ref(0) //打印数量合计
let tempStyle=ref("")//模板样式
let LODOP;
onMounted(() => {
  tableData.value = props.detailData.map(item => {
    item.printNum = 1
    return item
  })
  printNumTotal.value =  tableData.value.length

  setTimeout(() => {
    LODOP = getLodop();
    getPrinterCount()
  }, 500)

  getGoodsTempList()
})

const emits = defineEmits(['cancel'])

function handleClose() {
  emits('cancel')
}

//删除
function handleDelete(row) {
  tableData.value = tableData.value.filter(item => item.putawayId !== row.putawayId)
}

//批下
function clickBatchNum() {
  tableData.value = tableData.value.map(item => {
    item.printNum = tableData.value[0].printNum
    return item
  })
  changePrintNum()
}

//删除所选
function batchDelete() {
  const $table = proxy.$refs.tablePrintRef
  if ($table) {
    const selectRecords = $table.getCheckboxRecords()
    if (selectRecords.length === 0) {
      proxy.$modal.msgWarning("请选择要删除的数据!")
    } else {
      tableData.value = tableData.value.filter(item => !selectRecords.some(selObj => selObj.putawayId === item.putawayId))
    }
  }
}

//获取打印机
function getPrinterCount() {
  LODOP = getLodop();
  if (LODOP) {
    //获取打印机个数
    let printNum = LODOP.GET_PRINTER_COUNT();
    for (let i = 0; i < printNum; i++) {
      printNameList.value.push(LODOP.GET_PRINTER_NAME(i))
    }
  }
}
//预览
function clickView(row) {
  printData.value = [row]
  printFunc(row)
}
function clickPrint() {
  printData.value =tableData.value
  for (let i = 0; i <tableData.value.length ; i++) {
    let printObj =tableData.value[i]

    if(printObj.printNum && printObj.printNum *1 >1){
      //同一个库位条码打印多次
      for (let j = 0; j <printObj.printNum*1 ; j++) {
        printFunc(printObj,true)
      }
    }else{
      printFunc(printObj,true)
    }

  }
}

//打印并关闭
function clickPrintAndClose() {
  clickPrint()
  setTimeout(()=>{
    handleClose()
  },1000)
}
//打印方法
function printFunc(printData,isPrint){
  nextTick(() => {
    JsBarcode("#barcode" + printData.putawayId, printData.skuCode, {
      fontSize: 28,
      fontOptions: 'bold',
      displayValue: true //是否在条形码下方显示文字
    });
    let tempData = printTempList.value.filter(temp => temp.printConfigId === printTemp.value)[0] //获取模板数据
    //根据纸张大小控制 条码大小
    document.querySelector("#barcode" + printData.putawayId).style.width = tempData.width *0.9+ "mm"
    document.querySelector("#barcode" + printData.putawayId).style.height = tempData.height * 0.4 + "mm"
    //根据纸张大小 控制字体大小
    if (tempData.height * 1 >= 40) {
      document.querySelector(".skuFont").style.fontSize = '10pt'
    } else {
      document.querySelector(".skuFont").style.fontSize = '6pt'
    }

    let strFormHtml = document.querySelector("#printDiv" + printData.putawayId).innerHTML
    LODOP.PRINT_INIT('')//初始化
    LODOP.SET_PRINT_PAGESIZE(1, tempData.width * 10, tempData.height * 10)//设置纸张大小
    LODOP.ADD_PRINT_HTM('1%', '1%', '98%', '98%', strFormHtml) //设置打印内容
    LODOP.SET_PRINTER_INDEX(printMachine.value) //设置打印机
    if(isPrint){
      LODOP.PRINT()
    }else{
      LODOP.PREVIEW()
    }


  })
}
//获取库位模板
function getGoodsTempList() {
  let params = {
    pageSize: 0,
    param: {printType: 2, statusSort: true}
  }
  getPrintConfigList(params).then(res => {
    if (res.code === 200) {
      printTempList.value = res.data
      //设置默认模板 和默认打印机,样式
      printTemp.value = res.data[0].printConfigId
      printMachine.value = res.data[0].printMachine
      let tempData = printTempList.value.filter(temp => temp.printConfigId === printTemp.value)[0] //获取模板数据
      tempStyle.value=tempData.printStyle
    }
  })

}

function changePrintNum(){
  printNumTotal.value =0
  tableData.value.map(item=>{
    printNumTotal.value+=item.printNum *1
  })
}

//选择模板
function changeTemp(){
  let tempData = printTempList.value.filter(temp => temp.printConfigId === printTemp.value)[0] //获取模板数据
  tempStyle.value=tempData.printStyle
}
</script>

<style scoped lang="scss">

</style>